public class Solution {
    public String longestCommonPrefix(String[] strs) {
        //如果字符串数组为空，直接返回空字符串
        if(strs == null || strs.length == 0) {
            return "";
        }

        //初始公共前缀为第一个字符串
        String commonPrefix = strs[0];

        //遍历剩余的字符串
        for(int i = 1;i < strs.length;i++) {
            //比较当前字符串与当前最长公共前缀，更新最长公共前缀
            commonPrefix = getCommonPrefix(commonPrefix,strs[i]);

            //如果最长公共前缀已经为空，直接返回
            if(commonPrefix.equals("")) {
                return "";
            }
        }
        //返回最长公共前缀
        return commonPrefix;
    }

    //辅助函数，用于获取两个字符串的公共前缀
    private String getCommonPrefix(String str1,String str2) {
        int index = 0;
        //找到两个字符串的公共前缀的长度
        while(index < str1.length() && index < str2.length() && str1.charAt(index) == str2.charAt(index)) {
            index++;
        }
        //返回公共前缀
        return str1.substring(0,index);
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        String strs = "flower";
        String str1 = "flow";
        String str2 = "flight";
        System.out.println(solution.getCommonPrefix(str1,str2));
    }
}
